package com.bestvike.stone.spring.client.ssl;

import org.springframework.http.client.SimpleClientHttpRequestFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.net.HttpURLConnection;

/**
 * Created by 许崇雷 on 2019-02-21.
 */
public final class SkipSslVerificationHttpRequestFactory extends SimpleClientHttpRequestFactory {
    private final HostnameVerifier hostnameVerifier;
    private final SSLSocketFactory socketFactory;

    public SkipSslVerificationHttpRequestFactory() {
        this.hostnameVerifier = SkipHostnameVerifier.DEFAULT;
        try {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[]{SkipX509TrustManager.DEFAULT}, null);
            this.socketFactory = context.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException("init SkipSslVerificationHttpRequestFactory fail", e);
        }
    }

    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
        if (connection instanceof HttpsURLConnection)
            this.prepareHttpsConnection((HttpsURLConnection) connection);
        super.prepareConnection(connection, httpMethod);
    }

    private void prepareHttpsConnection(HttpsURLConnection connection) {
        connection.setHostnameVerifier(this.hostnameVerifier);
        connection.setSSLSocketFactory(this.socketFactory);
    }
}
